﻿using MachineVision.Shared.Extensions;
using MachineVision.Shared.Services;
using MachineVision.Shared.Services.Models;
using MachineVision.Shared.Services.Tables;

namespace MachineVision.Defect.Services
{
    public class ProjectService(IAppMapper appMapper) : BaseService, IProjectService
    {
        public async Task CreateOrUpdateAsync(ProjectModel input)
        {
            var proj = appMapper.Mapper<Project>(input);
            if (input.Id > 0)
            {
                var model = await SqlLite
                    .Select<Project>()
                    .Where(x => x.Id == proj.Id)
                    .FirstAsync();
                if (model != null)
                {
                    await SqlLite
                        .Update<Project>()
                        .SetDto(proj)
                        .Where(x => x.Id == model.Id)
                        .ExecuteAffrowsAsync();
                }
            }
            else
            {
                var model = await SqlLite.Select<Project>().FirstAsync(x => x.Id == proj.Id);
                if (!model)
                {
                    await SqlLite.Insert<Project>(proj).ExecuteAffrowsAsync();
                }
            }
        }

        public async Task DeleteAsync(int id)
        {
            await SqlLite.Delete<Project>().Where(x => x.Id == id).ExecuteAffrowsAsync();
        }

        public async Task<List<ProjectModel>> GetListAsync(string fillter)
        {
            var models = await SqlLite
                .Select<Project>()
                .Where(x => x.Name.Contains(fillter))
                .ToListAsync();
            return appMapper.Mapper<List<ProjectModel>>(models);
        }

        public async Task<ProjectModel> GetProjectByIdAsync(int id)
        {
            var result = await SqlLite.Select<Project>().Where(x => x.Id == id).FirstAsync();
            if (result != null)
                return appMapper.Mapper<ProjectModel>(result);
            else
                return null;
        }
    }
}
